
package com.pig4cloud.pig.common.data.config;

import com.baomidou.mybatisplus.annotation.DbType;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.pig4cloud.pig.common.data.tenant.PanguTenantHandler;
import com.pig4cloud.pig.common.data.tenant.TenantConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 * @author chengang
 * @date 2021/09/13
 */
@Configuration
@ConditionalOnBean(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
//@EnableConfigurationProperties(TenantConfigProperties.class)
public class MybatisPlusConfig {

	@Bean
	@ConditionalOnMissingBean
	public PanguTenantHandler panguTenantHandler() {
		return new PanguTenantHandler();
	}

	@Autowired
	private TenantConfigProperties tenantProperties;

	@Bean
	@ConditionalOnMissingBean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		boolean enableTenant = tenantProperties.getEnable();
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		if (enableTenant) {
			interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(panguTenantHandler()));
		}
		PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
		paginationInnerInterceptor.setOverflow(true);
		interceptor.addInnerInterceptor(paginationInnerInterceptor);
		return interceptor;
	}

}
